package cn.itcast.store.dao.daoImp;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.itcast.store.dao.CategoryDao;
import cn.itcast.store.domain.Category;
import cn.itcast.store.utils.JDBCUtils;

public class CategoryDaoImp implements CategoryDao {

	@Override
	public List<Category> findAllCats() throws SQLException {
		String sql="select * from category";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		 List<Category> list = qr.query(sql, new BeanListHandler<Category>(Category.class));
		System.out.println("数据库查询结果"+list);
		return list;
	}

	@Override
	public void addCategory(Category c) {
		String sql="insert into category values (? ,?)";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		try {
			qr.update(sql, c.getCid(),c.getCname());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public Category findCategoryByCid(String cid) throws SQLException {
		String sql="select * from category where cid=?";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		return qr.query(sql, new BeanHandler<Category>(Category.class),cid);
		
	}

	@Override
	public void EditSaveCategory(Category category) {
		//UPDATE orders SET ordertime=? ,total=? ,state= ?, address=?,NAME=?, telephone =? WHERE oid=?
		String Sql="update Category set cname=? where cid =? ";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		try {
			qr.update(Sql,category.getCname(),category.getCid() );
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void deleteCategory(String cid) {
		String sql ="delete from Category  where cid=?";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		try {
			qr.update(sql,cid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void setProductCid(String cid) {
		String sql ="Update Product set cid =null where cid=?";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		try {
			qr.update(sql,cid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
